<template>
  <el-dialog
    :title="this.attr_id ? '修改参数' : '添加参数'"
    :visible="isDynamicSwitch"
    width="50%"
    @close="paramsClosed"
  >
    <!-- 添加参数/属性的表单 -->
    <el-form
      :model="addForm"
      :rules="addFormRules"
      ref="addFormRef"
      label-width="100px"
    >
      <el-form-item
        :label="this.attr_id ? '修改参数' : '添加参数'"
        prop="attr_name"
      >
        <el-input v-model="addForm.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="paramsClosed">取 消</el-button>
      <el-button type="primary" @click="config">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addParams, theQueryParams, editorAddParams } from '@/api/params'
export default {
  props: {
    isDynamicSwitch: {
      type: Boolean,
      default: false
    },
    activeName: {
      type: String
    },
    cateId: {
      type: Number
    },
    attr_id: {
      type: Number
    }
  },
  data() {
    return {
      // 添加参数/属性表单的数据对象
      addForm: {
        attr_name: ''
      },
      // 表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 判断传递的值
    config() {
      if (this.attr_id) {
        // 编辑
        this.editParams()
      } else {
        // 添加
        this.requirdDynamic()
      }
    },
    // 对话框 关闭操作
    paramsClosed() {
      this.$refs.addFormRef.resetFields()
      this.$emit('update:attr_id', null)
      this.$emit('update:isDynamicSwitch', false)
    },
    // 添加动态参数或者静态属性
    async requirdDynamic() {
      try {
        this.$refs.addFormRef.validate()
        const res = await addParams({
          id: this.cateId,
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status === 201) {
          this.$emit('getUpdateData')
          this.$emit('update:isDynamicSwitch', false)
          this.$message.success('添加成功')
        }
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    // 父组件调用子组件 回调
    async editCall(id) {
      const res = await theQueryParams({
        id: this.cateId,
        attrId: id,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.addForm = res.data
    },
    // 点击按钮 修改操作
    async editParams() {
      try {
        this.$refs.addFormRef.validate()
        const res = await editorAddParams({
          id: this.cateId,
          attrId: this.addForm.attr_id,
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status === 200) {
          this.$message.success('更新成功')
          this.$emit('getUpdateData')
          this.$emit('update:isDynamicSwitch', false)
        }
      } catch (error) {
        this.$message.error('更新失败')
      }
    }
  }
}
</script>
